package policy

import (
	"crypto/sha1"
	"encoding/hex"
	"fmt"

	"gitee.com/hexug/devcloud/mcenter/common/logger"
	"gitee.com/hexug/devcloud/mcenter/common/meta"
)

func NewCreatePolicyRequest() *CreatePolicyRequest {
	return &CreatePolicyRequest{}
}

func NewPolicySet() *PolicySet {
	return &PolicySet{
		Items: []*Policy{},
	}
}

func (p *PolicySet) GetUserIds() (uids []string) {
	for _, uid := range p.Items {
		uids = append(uids, uid.Meta.Id)
	}
	return
}

func NewPolicy(in *CreatePolicyRequest) *Policy {
	d := meta.NewMeta()
	sh := sha1.New()
	if _, err := sh.Write([]byte(fmt.Sprintf("%s.%s.%s", in.UserId, in.Namespces, in.RoleId))); err != nil {
		logger.L().Error(err.Error())
		return nil
	}
	d.Id = hex.EncodeToString(sh.Sum(nil))
	return &Policy{
		Meta: d,
		Spec: in,
	}
}
func New() *Policy {
	return &Policy{
		Meta: &meta.Meta{},
		Spec: NewCreatePolicyRequest(),
	}
}

func NewQueryPolicyRequest() *QueryPolicyRequest {
	return &QueryPolicyRequest{}
}
func NewQueryPolicyRequestValidata() *QueryPolicyRequest {
	return &QueryPolicyRequest{
		IsValidate: true,
	}
}

func NewDetailPolicyRequest(id string) *DetailPolicyRequest {
	return &DetailPolicyRequest{
		PolicyId: id,
	}
}
